package com.desaysv.wandroid.utils;

import android.util.Log;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author linzi
 * @date 2023-1-11
 */
public class UDPUtils {
    private static final String TAG = "[UDPUtils]";
    private UDPUtils(){}
    public static void startService(){
        new Thread(new Runnable() {
            @Override
            public void run() {
//                try {
//                    DatagramSocket datagramSocket = new DatagramSocket(9999);
//                    byte[] data=new byte[1024];
//                    DatagramPacket pact=new DatagramPacket(data, data.length);
//                    while (true){
//                        datagramSocket.receive(pact);
//                        String dataStr=new String(pact.getData(),0, pact.getLength());
//                        Log.e(TAG, "udpservice:"+dataStr);
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
                try {
                    ServerSocket serverSocket=new ServerSocket(9999);
                    Log.e(TAG, "tcprun: server===>"+serverSocket.isClosed() );
                    while (true){
                        Socket client = serverSocket.accept();
                        Log.e(TAG, "tcprun: client connect:"+client.getInetAddress().getHostAddress() );
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public static void startClient(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DatagramSocket datagramSocket = new DatagramSocket(9998);
                    String data="info----";
                    for (int i = 0; i < 10; i++) {
                        Thread.sleep(1000);
                        byte[]dataB=(data+i).getBytes();
                        DatagramPacket packet=new DatagramPacket(dataB, dataB.length, InetAddress.getByName("127.0.0.1"),9999);
                        datagramSocket.send(packet);
                        Log.e(TAG, "udpclient:"+new String(dataB));
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
